﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WorkHelperWCF.Model;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.Services;
using System.Data.Services.Common;
using System.ServiceModel.Web;

namespace WorkHelperWCF
{
    public class WorkHelperService : IWorkHelperService
    {
        public EFDbContext context = new EFDbContext();
        public Boolean saveUser(string information, string password, int userid, string username)
        {
            User user = new User() { userid = userid, username = username, password = password, information = information };
            bool isNew;
            try
            {
                //if (user != null)
                    isNew = context.users.Where(u => u.username == username && u.password == password).First() != null;
                //else
                //    throw new InvalidOperationException();
            }
            catch (InvalidOperationException)
            {
                isNew = true;
            }

            if (!isNew && context.users.Where(u => user.username == u.username && user.password == u.password).FirstOrDefault() != null)
                context.users.Remove(context.users.Where(u => user.username == u.username && user.password == u.password).FirstOrDefault());
            
            context.users.Add(user);
            context.SaveChanges();
            return true;
        }

        public User getUser(string username, string password)
        {
            try
            {
                return context.users.Where(u => u.username == username && u.password == password).FirstOrDefault() ?? null;
            }
            catch (ArgumentNullException)
            {
                return null;
            }
        }


        public bool saveUserService(User user)
        {
            return saveUser(user.information, user.password, user.userid, user.username);
        }
    }
}
